import sys
import random
from math import exp,sqrt
from getopt import getopt
from time import clock

def dot(x,y):
	s = 0.0
	for i in x:
		s += x[i]*y.get(i,0)
	return s

def readSVMlight(f):
    ret=[]
    for line in f:
        n=line.find('#')
        line=line[0:n].strip()
        if not line: continue
        s=line.split()
        vector=eval('{'+', '.join(s[1:])+'}')
        label=int(s[0])
        ret.append((vector,label))
    f.close()
    return ret

def writeSVMlight(data,f):
    for x,y in data:
        f.write("%d " % y)
        keys=x.keys();
        keys.sort()
        for k in keys:
            if x[k]!=0:
                f.write("%d:%g " % (k,x[k]))
        f.write("\n")
    f.close()

def normalizemax(data,maximum):
    if maximum is None:
        maximum=max((sqrt(dot(x,x)) for x,y in data))
    for x,y in data:
        for k in x.iterkeys():
            x[k]/=maximum
    print maximum

def normalizeavg(data,avg):
    if avg is None:
        avg=sum((sqrt(dot(x,x)) for x,y in data))/len(data)
    for x,y in data:
        for k in x.iterkeys():
            x[k]/=avg
    print avg

if __name__=='__main__':
    norms={
            'avg':normalizeavg,
            'max':normalizemax
            }
    options={
            '-n':'avg',
            '-o':'.norm'
            }
    optlist,args=getopt(sys.argv[1:], 'n:o:v:')
    options.update(dict(optlist))
    if (len(args)==0):
        print 'Missing input file'
        sys.exit(1)
    if '-v' in options:
        val=float(options['-v'])
    else:
        val=None
    normalize=norms[options['-n']]
    f=open(args[0])
    examples=readSVMlight(f)
    normalize(examples,val)
    f=open(args[0]+options['-o'],'w')
    writeSVMlight(examples,f)
